# -*- coding: utf-8 -*-
# @Time : 2023/10/25 20:32
# @Author : ZH
# @File : 16.py
# @Software: PyCharm
from typing import List


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        min_num = None
        h = 0
        for i in range(len(nums)):
            num1 = nums[i]
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            for l_index in range(i + 1, len(nums)):
                if l_index > i + 1 and nums[l_index] == nums[l_index - 1]:
                    continue
                r_index = l_index + 1
                while r_index < len(nums):
                    if min_num:
                        nums_ = target - num1 - nums[l_index] - nums[r_index]
                        nums_ = nums_ if nums_ >=0 else 0-nums_
                        if min_num >= nums_:
                            min_num = nums_
                            h = num1 + nums[l_index] + nums[r_index]
                            # print(min_num, h)
                        else:
                            return h
                    else:
                        min_num = target - num1 - nums[l_index] - nums[r_index]
                        h = num1 + nums[l_index] + nums[r_index]
                    r_index += 1
        return h


if __name__ == '__main__':
    so = Solution()
    l = so.threeSumClosest(nums=[1,1,1,0], target=-100)
    print(l)
